package com.kaixuan.mvvmdemo.viewmodule;

import com.kaixuan.mvvmdemo.bean.LoginReq;
import com.kaixuan.mvvmdemo.bean.LoginRsp;
import com.kaixuan.mvvmdemo.http.BanMaApi;
import com.kaixuan.mvvmdemo.view.ILoginView;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * Created by kaixuan on 2017/3/23.
 */

public class LoginViewModule {

    private ILoginView loginView;

    public LoginViewModule(ILoginView loginView) {
        this.loginView = loginView;
    }

    public void login() {
        try {
            Retrofit retrofit = new Retrofit.Builder()
                    .addConverterFactory(GsonConverterFactory.create())//解析方法
                    .baseUrl("http://112.74.214.109:8080/gym/gym/")
                    .build();
            retrofit.create(BanMaApi.class)
                    .login(new LoginReq(loginView.getUserName(), loginView.getPassword()))
                    .enqueue(new Callback<LoginRsp>() {
                        @Override
                        public void onResponse(Call<LoginRsp> call, Response<LoginRsp> response) {

//                            try {
//
//                                Log.e("response",new Gson().toJson(response.body()));
//                            } catch (Exception e) {
//                                e.printStackTrace();
//                            }
                            try {
                                if (response.code() != 200){
//                                    loginView.onLoginFail("登录失败，"+response.errorBody().string());
                                    loginView.onLoginFail("登录失败，"+response.body().getErrMsg());
                                }else {
                                    loginView.onLoginSuccess("登录成功，您的名字是" + response.body().getUser().getNickname());
                                }
                            }catch (Exception e){
                                e.printStackTrace();
                            }
                        }

                        @Override
                        public void onFailure(Call<LoginRsp> call, Throwable t) {
                            loginView.onLoginFail("登录失败，"+t.getMessage());
                        }
                    });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
